package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.CountryTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.StateTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.WarrantiesTable;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.Warranty_Country_State;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.util.DateUtis;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class WarrantyDetailActivity extends Activity implements AsyncQueryListener {

	private final static String TAG = WarrantyDetailActivity.class.getSimpleName();
	private static final int MAP_PICKER = 57;

	private NotifyingAsyncQueryHandler mHandler;
	private TextView productName;
	private TextView manufacturer;
	private TextView description;
	private TextView storeName;
	private TextView purchaseDate;
	private TextView endDate;
	private ImageView callButtom;
	private ImageView emailButtom;
	private ImageView findStore;
	private double lat = 0d;
	private double lng = 0d;

	private String phoneNumber;
	private String serviceEmail;
	private String warrantyId = "";
	private String retailStoreId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.warranity_detail);

		productName = (TextView) findViewById(R.id.product_name_value);
		manufacturer = (TextView) findViewById(R.id.manufacturer_name_value);
		purchaseDate = (TextView) findViewById(R.id.purchase_date_value);
		endDate = (TextView) findViewById(R.id.expiration_date_value);
		description = (TextView) findViewById(R.id.description_value);
		storeName = (TextView) findViewById(R.id.store_name_value);
		callButtom = (ImageView) findViewById(R.id.call_button);
		emailButtom = (ImageView) findViewById(R.id.email_button);
		findStore = (ImageView) findViewById(R.id.find_store);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		String id = getIntent().getExtras().getString(Keys._warrantyId);

		String[] projectionWarranty = { WarrantiesTable._ID, WarrantiesTable.WARRANTY_ID, WarrantiesTable.PRODUCT_PRICE, WarrantiesTable.PRODUCT_NAME, WarrantiesTable.MANUFACTURER_NAME,
				WarrantiesTable.END_DATE, WarrantiesTable.PURCHASE_DATE, WarrantiesTable.RETAIL_STORE_NAME, WarrantiesTable.ADDRESS_CITY, WarrantiesTable.SERVICE_NUMBER, CountryTable.NAME,
				StateTable.STATE_NAME, WarrantiesTable.AREA_LIMIT_TEXT, WarrantiesTable.LATITUDE, WarrantiesTable.LONGTITUDE, WarrantiesTable.ADDRESS_POSTAL_CODE, WarrantiesTable.IMAGE_URL,
				WarrantiesTable.ADDRESS_STREET, WarrantiesTable.SERVICE_EMAIL, WarrantiesTable.RETAIL_STORE_ID, WarrantiesTable.RETAIL_NAME };
		mHandler.startQuery(QueriesCodes.WARRANTY_BY_ACCOUNT_ID, Warranty_Country_State.CONTENT_URI, projectionWarranty, WarrantiesTable.TABLE_NAME + "." + WarrantiesTable.WARRANTY_ID
				+ " ='" + id + "'", null, null);

	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.WARRANTY_BY_ACCOUNT_ID:
			if (null != cursor) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					retailStoreId = cursor.getString(cursor.getColumnIndex(WarrantiesTable.RETAIL_STORE_ID));
					productName.setText(cursor.getString(cursor.getColumnIndex(WarrantiesTable.PRODUCT_NAME)));
					manufacturer.setText(cursor.getString(cursor.getColumnIndex(WarrantiesTable.MANUFACTURER_NAME)));
					purchaseDate.setText(DateUtis.parseDateFromMilliseconds(cursor.getLong(cursor.getColumnIndex(WarrantiesTable.PURCHASE_DATE))));
					endDate.setText(DateUtis.parseDate(cursor.getString(cursor.getColumnIndex(WarrantiesTable.END_DATE))));
					String descriptionValue = cursor.getString(cursor.getColumnIndex(WarrantiesTable.AREA_LIMIT_TEXT));
					if (descriptionValue != null)
						description.setText(Html.fromHtml(descriptionValue));

					String retailStoreName = cursor.getString(cursor.getColumnIndex(WarrantiesTable.RETAIL_STORE_NAME));
					String retailName = cursor.getString(cursor.getColumnIndex(WarrantiesTable.RETAIL_NAME));
					String result = (retailStoreName == null) ? retailName : retailStoreName;
					storeName.setText(result);

					phoneNumber = cursor.getString(cursor.getColumnIndex(WarrantiesTable.SERVICE_NUMBER));
					if (null == phoneNumber)
						callButtom.setEnabled(false);
					serviceEmail = cursor.getString(cursor.getColumnIndex(WarrantiesTable.SERVICE_EMAIL));
					if (serviceEmail == null)
						emailButtom.setEnabled(false);

					warrantyId = cursor.getString(cursor.getColumnIndex(WarrantiesTable.WARRANTY_ID));
					lat = cursor.getDouble(cursor.getColumnIndex(WarrantiesTable.LATITUDE));
					lng = cursor.getDouble(cursor.getColumnIndex(WarrantiesTable.LONGTITUDE));
					if (lat == 0d && lng == 0d)
						findStore.setEnabled(false);

				}
			}

			break;
		}
	}

	public void doServiceCall(View view) {
		try {
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse("tel:" + phoneNumber));
			startActivity(callIntent);
		} catch (ActivityNotFoundException e) {
			Log.e(TAG, "Call failed", e);
		}
	}

	public void doEmailSend(View view) {
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, description.getText().toString());
		emailIntent.setType("plain/text");
		emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { serviceEmail });
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name));
		try {
			startActivity(Intent.createChooser(emailIntent, getString(R.string.choose_variant)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void doFindStores(View view) {
		showDialog(MAP_PICKER);
	}

	public void doTransfer(View view) {
		Intent intent = new Intent(getApplicationContext(), TransferEmailActivity.class);
		intent.putExtra(Keys._warrantyId, warrantyId);
		startActivity(intent);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		switch (id) {
		case MAP_PICKER:
			View mapChooserView = mInflater.inflate(R.layout.map_chooser, null);
			Button buildPath = (Button) mapChooserView.findViewById(R.id.button_path);
			Button showOnMap = (Button) mapChooserView.findViewById(R.id.button_map);

			buildPath.setOnClickListener(new android.view.View.OnClickListener() {

				@Override
				public void onClick(View v) {
					final String uri = "geo:" + lat + "," + lng + "?q=" + lat + "," + lng + " (" + storeName.getText().toString() + ")";
					// final String uri = "geo:" + lat + "," + lng;// + "?q=" +
					// storeName.getText().toString();
					final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					getApplicationContext().startActivity(i);
					dismissDialog(MAP_PICKER);
				}
			});

			showOnMap.setOnClickListener(new android.view.View.OnClickListener() {

				@Override
				public void onClick(View v) {
					final Intent intent = new Intent(getApplicationContext(), MapActivity.class);
					intent.putExtra(Keys._retailStoreId, retailStoreId);
					intent.putExtra(Keys.latitude, lat);
					intent.putExtra(Keys.longtitude, lng);
					startActivity(intent);
					dismissDialog(MAP_PICKER);
				}
			});

			AlertDialog.Builder builderMap = new AlertDialog.Builder(this);
			builderMap.setNegativeButton(android.R.string.cancel, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builderMap.setView(mapChooserView);
			builderMap.setMessage(getString(R.string.choose_variant));

			builderMap.setCancelable(true);
			return builderMap.create();

		default:
			break;
		}
		return null;
	}

}
